import { requestClient } from '#/api/request';

export namespace TenantApi {
  export type TenantStatus = 'active' | 'inactive' | 'suspended';
  export type TenantType = 'individual' | 'enterprise';

  export interface TenantRecord {
    id: number;
    name: string;
    company_name?: string | null;
    tax_registration_number?: string | null;
    address?: string | null;
    bank_name?: string | null;
    bank_account?: string | null;
    invoice_contact_phone?: string | null;
    invoice_mailing_address?: string | null;
    invoice_recipient?: string | null;
    tenant_type: TenantType;
    contact_phone?: string | null;
    contact_email?: string | null;
    service_fee_rate: number;
    status: TenantStatus;
    account_balance: number;
    invoiceable_amount: number;
    settings?: Record<string, any> | null;
    created_at: string;
    updated_at: string;
    creator?: {
      id: number;
      name: string;
    } | null;
  }

  export interface TenantListResponse {
    items: TenantRecord[];
    total: number;
  }

  export interface UpsertTenantPayload {
    name: string;
    company_name: string;
    tax_registration_number: string;
    address: string;
    bank_name: string;
    bank_account: string;
    contact_phone: string;
    contact_email: string;
    service_fee_rate: number;
    tenant_type?: TenantType;
  }

  export interface TenantInitialAccount {
    id: number | string;
    username: string;
    email: string | null;
    phone: string | null;
    plain_password: string;
  }

  export interface CreateTenantResponse {
    tenant: TenantRecord;
    initial_account: TenantInitialAccount;
  }

  export interface TenantStatistics {
    user_count: number;
    active_user_count: number;
    latest_settlement_at: string | null;
  }

  export interface TenantDetailResponse {
    tenant: TenantRecord;
    statistics: TenantStatistics;
  }
}

export async function getTenantsApi() {
  return requestClient.get<TenantApi.TenantListResponse>('/api/admin/tenants');
}

export async function createTenantApi(payload: TenantApi.UpsertTenantPayload) {
  return requestClient.post<TenantApi.CreateTenantResponse>('/api/admin/tenants', payload);
}

export async function updateTenantApi(id: number, payload: TenantApi.UpsertTenantPayload) {
  return requestClient.put<TenantApi.TenantRecord>(`/api/admin/tenants/${id}`, payload);
}

export async function updateTenantStatusApi(id: number, status: TenantApi.TenantStatus) {
  return requestClient.put<TenantApi.TenantRecord>(`/api/admin/tenants/${id}/status`, { status });
}

export async function getTenantDetailApi(id: number | string) {
  return requestClient.get<TenantApi.TenantDetailResponse>(`/api/admin/tenants/${id}`);
}
